package com.ruoyi.project.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.domain.vo.ProductVo;
import com.ruoyi.project.system.mapper.*;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysProductService;
import com.ruoyi.project.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysQueryPayMapper sysQueryPayMapper;

    @Autowired
    private SysEarningsMapper sysEarningsMapper;

    @Autowired
    private SysExtractMapper sysExtractMapper;

    @Autowired
    private ISysProductService iSysProductService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserProductPriceMapper supppm;

    @Autowired
    protected Validator validator;

    @Override
    public List<UserCustomized> userProfit(UserCustomized userCustomized) {
        userCustomized.setNum((userCustomized.getNum() - 1) * userCustomized.getSize());
        List<SysUser> users = userMapper.selectUsers(userCustomized);
        List<UserCustomized> ucs = new ArrayList<>();
        for (SysUser user : users) {
            user = getUserLevel(user);
            Float earnings = sysQueryPayMapper.sumBrokerage(user.getUserId());
            earnings += sysQueryPayMapper.sumRoyaltyByParent(user.getUserId());
            earnings += sysEarningsMapper.sumEarningsByUserId(user.getUserId());
            Float extract = sysExtractMapper.sumExtractByUserId(user.getUserId());
            ucs.add(new UserCustomized(user, BigDecimal.valueOf(earnings), BigDecimal.valueOf(extract)));
        }
        return ucs;
    }

    @Override
    public List<UserCustomized> customized(UserCustomized userCustomized) {
        userCustomized.setNum((userCustomized.getNum() - 1) * userCustomized.getSize());
        List<SysUser> users = userMapper.selectUsers(userCustomized);
        List<SysProduct> sysProducts = iSysProductService.selectSysProductList(new SysProduct("0"));
        List<Integer> allIds = sysProducts.stream().map(SysProduct::getProductId).collect(Collectors.toList());
        List<UserCustomized> ucs = new ArrayList<>();
        for (SysUser user : users) {
            user = getUserLevel(user);
            UserCustomized uc = new UserCustomized(user);
            List<SysUserProductPrice> sysUserProductPrices = supppm.selectSysUserProductPriceList(new SysUserProductPrice(user.getUserId()));
            List<Integer> partIds = sysUserProductPrices.stream().map(SysUserProductPrice::getProductId).collect(Collectors.toList());
            for (int i = 0; i < allIds.size(); i++) {
                ProductVo pvo;
                SysUserProductPrice supp;
                // 获取底价
                BigDecimal VIPPrice = iSysProductService.getSysUserLevelFloorPrice(sysProducts.get(i), user.getGrade());
                if (partIds.contains(allIds.get(i))) {
                    int index = partIds.indexOf(allIds.get(i));
                    supp = sysUserProductPrices.get(index);
                    pvo = new ProductVo(sysProducts.get(i));
                    if (supp.getCustomizedPrice() == null) {
                        pvo.setCustomizedPrice(VIPPrice);
                    } else {
                        pvo.setCustomizedPrice(supp.getCustomizedPrice());
                    }
                    if (supp.getRoyalty() == null) {
                        pvo.setRoyalty(sysProducts.get(i).getRoyalty());
                    } else {
                        pvo.setRoyalty(supp.getRoyalty());
                    }
                    if (supp.getBrokerage() == null) {
                        pvo.setBrokerage(sysProducts.get(i).getBrokerage());
                    } else {
                        pvo.setBrokerage(supp.getBrokerage());
                    }
                    if (supp.getMaxBrokerage() == null) {
                        pvo.setMaxBrokerage(sysProducts.get(i).getMaxBrokerage());
                    } else {
                        pvo.setMaxBrokerage(supp.getMaxBrokerage());
                    }
                    if (supp.getMaxRoyalty() == null) {
                        pvo.setMaxRoyalty(sysProducts.get(i).getMaxRoyalty());
                    } else {
                        pvo.setMaxRoyalty(supp.getMaxRoyalty());
                    }
                    BigDecimal supRoyalty = getSupRoyalty(sysProducts.get(i), user);
                    pvo.setSupRoyalty(supRoyalty);
                    pvo.setPrice(pvo.getCustomizedPrice().add(supRoyalty).add(pvo.getBrokerage()));
                    pvo.setDefaRoyalty(sysProducts.get(i).getRoyalty());
                } else {
                    // 获取底价
                    BigDecimal customizedPrice = iSysProductService.getSysUserLevelFloorPrice(sysProducts.get(i), user.getGrade());
                    BigDecimal supRoyalty = getSupRoyalty(sysProducts.get(i), user);
                    pvo = new ProductVo(sysProducts.get(i), customizedPrice, supRoyalty);
                    pvo.setDefaRoyalty(sysProducts.get(i).getRoyalty());
                }
                pvo.setVIPPrice(VIPPrice);
                uc.getSupps().add(pvo);
            }
            ucs.add(uc);
        }
        return ucs;
    }

    private BigDecimal getSupRoyalty(SysProduct sysProduct, SysUser user) {
        if (StringUtils.isNotEmpty(user.getParent())) {
            SysUserProductPrice sjupp = supppm.selectSysUserProductPrice(Long.parseLong(user.getParent()), sysProduct.getProductId());
            if (sjupp != null && sjupp.getRoyalty() != null) {
                return sjupp.getRoyalty();
            } else {
                return sysProduct.getRoyalty();
            }
        }
        return new BigDecimal(0);
    }

//    @Override
//    public SysUser getUserLevel(SysUser user) {
//        SysUser sysUser = userMapper.selectUserOne(user);
//        Map<String, Integer> orderNum = redisCache.getCacheMap(CacheConstants.LEVEL_ORDER_NUM_KEY);
//        Map<String, Integer> agencyNum = redisCache.getCacheMap(CacheConstants.LEVEL_AGENCY_NUM_KEY);
//        // 获取成功交易单数
//        int successPayCount = sysQueryPayMapper.selectSuccessPayCount(sysUser.getUserId());
//        int agencyCount = userMapper.selectAgencyCount(sysUser.getUserId());
//        String level;
//        if (successPayCount > orderNum.get("V5") && agencyCount >= agencyNum.get("V5")) {
//            level = "V5城市经理";
//        } else if (successPayCount > orderNum.get("V4") && agencyCount >= agencyNum.get("V4")) {
//            level = "V4团队经理";
//        } else if (successPayCount > orderNum.get("V3")) {
//            level = "V3";
//        } else if (successPayCount > orderNum.get("V2")) {
//            level = "V2";
//        } else if (successPayCount > orderNum.get("V1")) {
//            level = "V1";
//        } else {
//            level = "V0";
//        }
//        if (!level.equals(sysUser.getGrade())) {
//            // 级别与记录不对，修改
//            sysUser.setGrade(level);
//            userMapper.updateUser(new SysUser(sysUser.getUserId(), level));
//        }
//        return sysUser;
//    }

    @Override
    public SysUser getUserLevel(SysUser user) {
        SysUser sysUser = userMapper.selectUserOne(user);
        // 获取成功交易单数
        int successPayCount = sysQueryPayMapper.selectSuccessPayCount(sysUser.getUserId());
        int agencyCount = userMapper.selectAgencyCount(sysUser.getUserId());
        String level;
        if (successPayCount >= 100 && agencyCount >= 50) {
            level = "V5城市经理";
        } else if (successPayCount >= 80 && agencyCount >= 40) {
            level = "V4团队经理";
        } else if (successPayCount >= 50) {
            level = "V3";
        } else if (successPayCount >= 30) {
            level = "V2";
        } else if (successPayCount >= 20) {
            level = "V1";
        } else {
            level = "V0";
        }
        if (!level.equals(sysUser.getGrade())) {
            // 级别与记录不对，修改
            sysUser.setGrade(level);
            userMapper.updateUser(new SysUser(sysUser.getUserId(), level));
        }
        return sysUser;
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return null;
    }


    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);

        // 新增用户与角色管理
//        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }


    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }


    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
